﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Server
{
    internal class ServerSocket
    {
        public Socket socketServer;
        public Dictionary<int, ClientSocket> clientDic = new Dictionary<int, ClientSocket>();
        private bool isClose;
        public void Start(string ip,int port,int num)
        {
            isClose=false;
            socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ip), port);
            socketServer.Bind(ipPoint);
            socketServer.Listen(num);

            ThreadPool.QueueUserWorkItem(Accept);
            ThreadPool.QueueUserWorkItem(Receive);
        }
        private void Accept(object obj)
        {
            while (!isClose)
            {
                Socket socketClient = socketServer.Accept();
                ClientSocket client = new ClientSocket(socketClient);
                client.Send("欢迎连入服务器");
                clientDic.Add(client.clientID, client);
            }
        }

        private void Receive(object obj)
        {
            while (!isClose)
            {
                if(clientDic.Count>0)
                {
                    foreach(ClientSocket client in clientDic.Values)
                    {
                        client.Receive();
                    }
                }
            }
        }

        public void Close()
        {
            isClose = true;
            foreach (ClientSocket client in clientDic.Values)
            {
                client.Close();
            }
            clientDic.Clear();
            socketServer.Shutdown(SocketShutdown.Both);
            socketServer.Close();
        }
        public void Broadcast(string info)
        {
            foreach (ClientSocket client in clientDic.Values)
            {
                client.Send(info);
            }
        }
    }
}
